package com.kizuki.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestEfficiency {

    private volatile static Long num = 0L;

    public static void main(String[] args) {
        test1();
//        test2();
    }

    public static void test1() {
        Long start = System.currentTimeMillis();
        final Object lock = new Object();

        for (int i = 0; i < 7; i++) {
            new Thread(() -> {
                synchronized (lock) {
                    for (Long j = 0L; j < 10_00_0000L; j++) {
                        num++;
                    }
                }
            }).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(num);
        System.out.println(System.currentTimeMillis() - start); // 969
    }

    // 似乎lock效率高, 但和synchronized是同一量级的
    public static void test2() {
        long start = System.currentTimeMillis();
        Lock lock = new ReentrantLock();

        for (int i = 0; i < 7; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    for (Long j = 0L; j < 10_00_0000L; j++) {
                        num++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }).start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(num);
        System.out.println(System.currentTimeMillis() - start); // 868
    }

}


